package com.jiuli_travel.interceptor;

import com.jiuli_travel.user_service.model.entity.User;
import com.jiuli_travel.user_service.model.vo.UserVO;
import com.jiuli_travel.utils.RedisConstants;
import com.jiuli_travel.utils.UserHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.redisson.api.RBucket;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.web.servlet.HandlerInterceptor;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

public class LoginInterceptor implements HandlerInterceptor {


    private RedissonClient redissonClient;

    public LoginInterceptor(RedissonClient redissonClient){
        this.redissonClient = redissonClient;
    }
    /**
     * 拦截处理
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 校验用户是否已经登录 （ 或者说是否携带 token）
         */
        String token = request.getHeader("token");
        if(token == null){
            System.out.println("没有携带token");
            return false;
        }
        //从redis中取 （检验是否过期）
        UserVO userVO = (UserVO) redissonClient.getBucket(RedisConstants.LOGIN_USER_KEY + token).get();
        //未登录
        if(userVO == null){
            System.out.println("未登录");
            return false;
        }
        //设置信息到thread中
        UserHolder.saveUser(userVO);
        return true;
    }
}
